package com.eurasia.assignment.infrastructure.specification;

import org.springframework.data.jpa.domain.Specification;
import org.springframework.util.StringUtils;

import com.eurasia.assignment.controller.dto.ClassSearchRequest;
import com.eurasia.assignment.infrastructure.entity.ClassEntity;

/**
 * 班级查询规格类
 * 用于构建JPA Specification查询条件
 */
public class ClassSpecification {

    /**
     * 根据搜索条件创建班级查询规格
     * @param searchRequest 搜索请求参数
     * @return Specification<ClassEntity> 查询规格
     */
    public static Specification<ClassEntity> buildSpecification(ClassSearchRequest searchRequest) {
        // 使用更可靠的方式构建规格
        return (root, query, criteriaBuilder) -> {
            // 默认条件为true（匹配所有）
            var predicate = criteriaBuilder.conjunction();
            
            if (searchRequest != null) {
                // 班级名称模糊匹配
                if (StringUtils.hasText(searchRequest.getClassName())) {
                    predicate = criteriaBuilder.and(predicate, 
                        criteriaBuilder.like(root.get("className"), 
                            "%" + searchRequest.getClassName() + "%"));
                }
                
                // 年级精确匹配
                if (StringUtils.hasText(searchRequest.getGrade())) {
                    predicate = criteriaBuilder.and(predicate,
                        criteriaBuilder.equal(root.get("grade"), searchRequest.getGrade()));
                }
                
                // 专业精确匹配
                if (StringUtils.hasText(searchRequest.getMajor())) {
                    predicate = criteriaBuilder.and(predicate, 
                        criteriaBuilder.equal(root.get("major"), searchRequest.getMajor()));
                }
                
                // 辅导员模糊匹配
                if (StringUtils.hasText(searchRequest.getTutor())) {
                    predicate = criteriaBuilder.and(predicate, 
                        criteriaBuilder.like(root.get("tutor"), 
                            "%" + searchRequest.getTutor() + "%"));
                }
            }
            
            return predicate;
        };
    }
} 